<?php

namespace App\Kuafu\Banner\Service;

use App\Kuafu\Banner\Enum\BannerCodeEnum;
use App\Kuafu\Banner\Enum\BannerEnum;
use App\Kuafu\Banner\Exceptions\BannerException;
use App\Kuafu\Banner\Model\BannerCommonModel;
use App\Kuafu\Banner\Model\BannerModel;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Config\Service\ConfigClientService;
use App\Kuafu\CouponPackage\Service\CouponPackageService;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Service\AuthService;

class BannerService extends BaseService
{

    /**
     * 广告添加
     *
     * @param $request
     * @throws BannerException|\App\Kuafu\User\Exceptions\UserException
     */
    public static function addBanner($request)
    {
        $addBanner               = new BannerModel();
        $addBanner->configId     = $request->configId;
        $addBanner->imageUrl     = str_replace(config('other.IMAGE_URL'), '', $request->imageUrl);
        $addBanner->name         = $request->name;
        $addBanner->url          = $request->url;
        $addBanner->startTime    = strtotime($request->startTime);
        $addBanner->endTime      = strtotime($request->endTime);
        $addBanner->status       = $request->status;
        $addBanner->createdByUid = AuthService::getUserId();
        $addBanner->updatedByUid = AuthService::getUserId();
        try {
            $addBanner->save();
        } catch (\Exception $exception) {
            throw new BannerException(BannerCodeEnum::ERR_BANNER_DB_ADD, '新增失败', $exception);
        }
    }

    /**
     * 横幅列表
     *
     * @return array
     */
    public static function getBanner()
    {
        $banner     = new BannerModel();
        $bannerList = $banner::query()->get(['id', 'configId', 'imageUrl', 'name'])->toArray();
        foreach ($bannerList as &$value) {
            $value['imageUrl'] = config("other.IMAGE_URL") . $value['imageUrl'];
        }
        return $bannerList;
    }

    /**
     * 横幅删除（软删除）
     * @param int $id
     * @throws BannerException
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public static function delBanner(int $id): void
    {
        $query = BannerModel::query()->find($id);
        if (!$query) {
            throw new BannerException(BannerCodeEnum::ERR_BANNER_ID_NOT_EXIST);
        }

        $delConfig = BannerModel::delData($id);
        if (!$delConfig) {
            throw new BannerException(BannerCodeEnum::ERR_BANNER_DB_DEL);
        }
    }

    /**
     * 横幅修改
     *
     * @param $request
     * @throws BannerException
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public static function setBanner($request)
    {
        $data = [
            'imageUrl'     => str_replace(config("other.IMAGE_URL"), '', $request->imageUrl),
            "name"         => $request->name,
            "url"          => $request->url,
            "startTime"    => $request->startTime,
            "endTime"      => $request->endTime,
            "status"       => $request->status,
            "updatedByUid" => AuthService::getUserId(),
        ];

        $id = BannerModel::setData($request->id, $data);
        if (!$id) {
            throw new BannerException(BannerCodeEnum::ERR_BANNER_DB_SET, '编辑失败');
        }
    }

    /**
     *小程序横幅列表
     *
     * @param int $configId
     * @return array
     */
    public static function getBannerList(int $brandId, int $shopId): array
    {
        $banner = [];
        //查询后台配置banner图片
        $type         = BannerEnum::TYPE_BANNER;
        $shopInfo     = ShopService::getShopInfo($shopId);
        $field        = ['img', 'extraImg', 'name', 'id'];
        $bannerByType = BannerCommonModel::getBannerByType($type, $shopId, $shopInfo['type'], $field, 'get');
        if (empty($bannerByType->toArray())) {
            /*点餐小程序优化 不取默认图
             * $bannerDefault = ConfigClientService::getAppletDefaultHeaderBanner();
            foreach ($bannerDefault as $banners) {
                array_push($banner, [
                    'img'    => $banners,
                    'params' => new \stdClass(),
                    'type'   => ''
                ]);
            }*/
        } else {
            $bannerByType->each(function ($banners) use (&$banner) {
                array_push($banner, [
                    'img'    => $banners->img ? CommonService::joinImageUrl($banners->img) : "",
                    'params' => [
                        'targetId' => $banners->id
                    ],
                    'type'   => ''
                ]);
            });
        }
        $couponPackageBannerLists = CouponPackageService::getShopBanner($brandId, $shopId);
        if (!empty($couponPackageBannerLists)) {
            $couponPackageBannerLists->each(function ($couponPackageBanner) use (&$banner) {
                array_push($banner, [
                    'img'    => $couponPackageBanner->bannerImg ? CommonService::joinImageUrl($couponPackageBanner->bannerImg) : '',
                    'params' => [
                        'targetId' => $couponPackageBanner->id
                    ],
                    'type'   => 'couponPackage'
                ]);
            });
        }
        return [
            'banner' => $banner
        ];
    }

    /**
     * 小程序横幅详情
     *
     * @param int $id
     * @return array
     */
    public static function getBannerById(int $id): array
    {
        $getBannerById = BannerModel::query()->find($id);
        if (!$getBannerById) {
            return [];
        }
        $getBannerById['imageUrl'] = config("other.IMAGE_URL") . $getBannerById['imageUrl'];
        return $getBannerById->toArray();
    }


    /**
     * 商家APP banner
     * @return array
     */
    public static function getBannerByApp(): array
    {
        //商家APP bannerType的枚举为  4
        return BannerCommonModel::query()
            ->where('bannerType', BannerEnum::BANNER_TYPE_4)
            ->where('type', BannerEnum::TYPE_BANNER)
            ->where('status', BannerEnum::STATUS_ON)
            ->orderBy('sort')
            ->get()
            ->map(function ($item) {
                if ($item->effectiveType == BannerEnum::EFFECTIVE_TYPE_TIME_RANGE) {
                    if ($item->startAt < time() && $item->endAt > time()) {
                        return $item->img ? CommonService::joinImageUrl($item->img) : "";
                    }
                } else {
                    return $item->img ? CommonService::joinImageUrl($item->img) : "";
                }
            })->toArray();
    }


}
